﻿using System;
using System.Web.UI.WebControls;
using ETestIT.Core;
using ETestIT.Core.Infrastructure;
using ETestIT.UI.Presentation;
using ETestIT.UI.Presentation.Storage;
using SharpArch.Core.PersistenceSupport;

namespace ETestIT.UI
{
    public partial class Clients : PageBase<Clients>
    {
        private IRepository<Client> clientRepository;
        private ISessionProvider sessionProvider;
        protected void Page_Load(object sender, EventArgs e)
        {
            sessionProvider = IoC.Resolve<ISessionProvider>();
            clientRepository = IoC.Resolve<IRepository<Client>>();
            
            clientAddEdit.Update += ClientAddEditUpdate;
            
            if (!IsPostBack)
            {
                GetAllClients();
            }
        }

        private void GetAllClients()
        {
            gvClients.DataSource = clientRepository.GetAll();
            gvClients.DataBind();
        }

        protected void ClientAddEditUpdate(object sender, EventArgs e)
        {
            With.Transaction(() =>
            {
                var client = new Client();
                if (sessionProvider.Contains(Const.SelectedClientKey))
                                     {
                                         var clientId = sessionProvider.Get<int>(Const.SelectedClientKey);
                                         client = clientRepository.Get(clientId);
                                         sessionProvider.Remove(Const.SelectedClientKey);
                                     }
                clientAddEdit.UpdateModel(client);
                clientRepository.SaveOrUpdate(client);

                GetAllClients();

                Dialog.Information = "The clients list has been updated successfully";
            });
        }

        protected void GridCommand(object sender, CommandEventArgs e)
        {
            int commandId = int.Parse(e.CommandArgument.ToString());

            switch (e.CommandName)
            {
                case "ClientNew":
                case "ClientEdit":
                    {
                        var theClient = clientRepository.Get(commandId) ?? new Client();
                        clientAddEdit.ShowModel(theClient);

                        if (commandId != 0)
                            sessionProvider.Set(Const.SelectedClientKey, commandId);
                    }
                    break;
                case "ClientDelete":
                    {
                        With.Transaction(() =>
                        {
                            clientRepository.Delete(clientRepository.Get(commandId));
                            Dialog.Information = "The Client has been deleted successifully";
                        });

                        GetAllClients();
                    }
                    break;
            }
        }

    }
}
